package cn.edu.sctu.sctu_lysd.alipay;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;

import java.util.Map;

import cn.edu.sctu.sctu_lysd.R;
import cn.edu.sctu.sctu_lysd.base.BaseActivity;
import cn.edu.sctu.sctu_lysd.bean.JsonBaseBeen;
import cn.edu.sctu.sctu_lysd.bean.OrderData;
import cn.edu.sctu.sctu_lysd.databinding.ActivityPayOrderBinding;
import cn.edu.sctu.sctu_lysd.net.NetService;
import cn.edu.sctu.sctu_lysd.net.RetrofitHelper;
import cn.edu.sctu.sctu_lysd.utils.JumpUtils;
import cn.edu.sctu.sctu_lysd.utils.L;
import cn.edu.sctu.sctu_lysd.utils.ProgressUtil;
import cn.edu.sctu.sctu_lysd.view.act.IndexActivity;
import cn.edu.sctu.sctu_lysd.view.act.QRCodeAct;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 重要说明:
 * <p>
 * 这里只是为了方便直接向商户展示支付宝的整个支付流程；所以Demo中加签过程直接放在客户端完成；
 * 真实App里，privateKey等数据严禁放在客户端，加签过程务必要放在服务端完成；
 * 防止商户私密数据泄露，造成不必要的资金损失，及面临各种安全风险；
 */
public class PayActivity extends BaseActivity {

    private ActivityPayOrderBinding mBinding;

    private String orderStr = "";

    private NetService service;

    private long orderId;

    private long parcelId = -1;

    private static final int SDK_PAY_FLAG = 1;

    public final static String ORDER_ID_INTENT_TAG = "orderID";
    public final static String INTENT_TAG = "who_intent";

    public static final long DEPOSIT_TAG = 1;


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        Toast.makeText(PayActivity.this, "支付成功", Toast.LENGTH_SHORT).show();

                        //TODO: 服务器异步通知

                        Bundle bundle = new Bundle();

                        bundle.putLong(QRCodeAct.INTENT_PARCEL_ID, parcelId);

                        if (getIntent().getExtras().getLong(INTENT_TAG) != DEPOSIT_TAG){

                            JumpUtils.jumpActivity(PayActivity.this, QRCodeAct.class, bundle);

                        }else {

                            ProgressUtil.showAlertDialog("支付成功", "点击确定返回首页", PayActivity.this, new ProgressUtil.AlertDialogCallBack() {
                                @Override
                                public void submit() {
                                    JumpUtils.jumpActivity(PayActivity.this, IndexActivity.class);
                                }

                                @Override
                                public void cancel() {

                                }
                            });

                        }


                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(PayActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }
                default:
                    break;
            }
        }

        ;
    };


    @Override
    protected int getLayoutResource() {
        return R.layout.activity_pay_order;
    }

    @Override
    protected void initAfter(Object bind) {

        mBinding = (ActivityPayOrderBinding) bind;

        RetrofitHelper helper = RetrofitHelper.getInstance();

        service = (NetService) helper.getService(NetService.class);

        orderId = getIntent().getExtras().getLong(ORDER_ID_INTENT_TAG);

        L.e("orderId", orderId + "");

        getOrderStr();




    }


    private void getOrderStr() {

        Call<JsonBaseBeen<String>> callOrderStr = service.getOrderStr(orderId);

        callOrderStr.enqueue(new Callback<JsonBaseBeen<String>>() {
            @Override
            public void onResponse(Call<JsonBaseBeen<String>> call, Response<JsonBaseBeen<String>> response) {

                if (response.code() == 200){

                    orderStr = response.body().getData();

                    initData();
                }



            }

            @Override
            public void onFailure(Call<JsonBaseBeen<String>> call, Throwable t) {

            }
        });

    }

    private void initData() {

        Call<JsonBaseBeen<OrderData>> callOrder = service.getOrder(orderId);

        callOrder.enqueue(new Callback<JsonBaseBeen<OrderData>>() {
            @Override
            public void onResponse(Call<JsonBaseBeen<OrderData>> call, Response<JsonBaseBeen<OrderData>> response) {


                if (response.code() == 200){

                    mBinding.orderMessage.setText(response.body().getData().getOrderDescription());

                    L.e("orderId", response.body().getData().getOrderDescription());

                    parcelId = response.body().getData().getParcelId();

                    mBinding.orderPrice.setText(response.body().getData().getTotalAmount() + "");

                    mBinding.idPay.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            payV2();
                        }
                    });

                }



            }

            @Override
            public void onFailure(Call<JsonBaseBeen<OrderData>> call, Throwable t) {



            }
        });


    }


    /**
     * 支付宝支付业务
     *
     */
    public void payV2() {

        if (orderStr.equals("")) {

        } else {
            Runnable payRunnable = new Runnable() {

                @Override
                public void run() {
                    PayTask alipay = new PayTask(PayActivity.this);
                    Map<String, String> result = alipay.payV2(orderStr, true);
                    Log.i("msp", result.toString());

                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }
            };

            Thread payThread = new Thread(payRunnable);
            payThread.start();
        }

    }

    /**
     * get the sdk version. 获取SDK版本号
     */
    public void getSDKVersion() {
        PayTask payTask = new PayTask(this);
        String version = payTask.getVersion();
        Toast.makeText(this, version, Toast.LENGTH_SHORT).show();
    }
}
